package com.mio.web.controller.recommend;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.durcframework.core.GridResult;
import org.durcframework.core.MessageResult;
import org.durcframework.core.UserContext;
import org.durcframework.core.controller.CrudController;
import org.durcframework.core.expression.Expression;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.mio.web.common.MioConstants;
import com.mio.web.common.MioInfoTips;
import com.mio.web.common.MioUtil;
import com.mio.web.entity.product.Product;
import com.mio.web.entity.recommend.Recommand;
import com.mio.web.entity.recommend.RecommandSch;
import com.mio.web.service.recommend.RecommandService;
import org.durcframework.core.expression.ExpressionQuery;
import org.durcframework.core.expression.subexpression.ValueExpression;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ModelAndView;

import com.mio.web.common.MioConstants;
import com.mio.web.common.MioInfoTips;
import com.mio.web.common.MioUtil;
import com.mio.web.entity.recommend.Recommand;
import com.mio.web.entity.recommend.RecommandSch;
import com.mio.web.entity.sys.SysUpload;
import com.mio.web.service.recommend.RecommandService;
import com.mio.web.service.sys.SysUploadService;

import net.coobird.thumbnailator.Thumbnails;

@Controller
public class RecommandController extends
		CrudController<Recommand, RecommandService> {
	
	@Autowired
	private SysUploadService sysUploadService;
	
	@RequestMapping("/recommand.do")
	public ModelAndView getRecommandJsp(HttpServletRequest request){
		ModelAndView model = new ModelAndView("/recommend.jsp");
		//获取登录用户
		model.addObject("loginUser",UserContext.getInstance().getUser());
		//获取横幅
		SysUpload banner = sysUploadService.getFirstSysUploadByFuncId("recommendBanner");
		model.addObject("banner", banner);
		//获取当前页数以及总页数
		String pages = request.getParameter("pageStart");
		String pageTotal = request.getParameter("pageCount");
		ExpressionQuery query = new ExpressionQuery();
		query.addSort("sortId");
		query.setPageSize(20);
		int pageNum  = 1;
		if(pages != null){
			pageNum = Integer.parseInt(pages);
			query.setStart((pageNum-1)*20);
		}else{
			query.setStart(0);
		}
		//获取当前页数的美美推荐列表
		List<Recommand> recommands = this.getService().find(query);
		model.addObject("recommands",recommands);
		//设置起始页数
		model.addObject("pageStart", pageNum);
		int pageCount = 0;
		//判断是否有总页数的值
		if(pageTotal != null){
			int total = Integer.parseInt(pageTotal);
			pageCount = total;
		}else{
			//查询美美推荐的总页数
			query = new ExpressionQuery();
			pageCount = this.getService().findTotalCount(query)/20 + 1;
		}
		//设置总页数
		model.addObject("pageCount",pageCount);
		return model;
	}

	@RequestMapping("/recommandDetail.do")
	public ModelAndView getRecommandDetail(HttpServletRequest request){
		ModelAndView model = new ModelAndView("/recommendDetail.jsp");
		//获取登录用户
		model.addObject("loginUser",UserContext.getInstance().getUser());
		//获取横幅
		SysUpload banner = sysUploadService.getFirstSysUploadByFuncId("recommendBanner");
		model.addObject("banner", banner);
		String recommendId = request.getParameter("recommendId");
		Recommand recommend = this.getService().get(recommendId);
		model.addObject("recommend",recommend);
		return model;
	}
	
	//新增美美推荐
	@RequestMapping("/addRecommand.do")
	public @ResponseBody
	Map<String, Object> addRecommand(Recommand entity, HttpServletRequest request,
			HttpServletResponse response) throws IllegalStateException, IOException  {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			// 创建一个通用的多部分解析器
			CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
					request.getSession().getServletContext());
			// 判断 request 是否有文件上传,即多部分请求
			if (multipartResolver.isMultipart(request)) {
				String relPath = "/upload/recommend/";
				// 转换成多部分request
				MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
				// 取得request中的所有文件名
				Iterator<String> iter = multiRequest.getFileNames();
				List<SysUpload> sysUploads = new ArrayList<SysUpload>();
				String picId = "";
				int count = 0;
				//美美推荐图
				String productImg = "";
				while (iter.hasNext()) {
					System.out.println(iter.hasNext());
					count++;
					// 记录上传过程起始时的时间，用来计算上传时间
					int pre = (int) System.currentTimeMillis();
					// 取得上传文件
					MultipartFile file = multiRequest.getFile(iter.next());
					if (file != null) {
						// 取得当前上传文件的文件名称
						String fileName = file.getOriginalFilename();
						// 如果名称不为“”,说明该文件存在，否则说明该文件不存在
						if (!fileName.trim().equals("")) {
							System.out.println(fileName);						
							File targetFile = MioUtil.getUploadFile(request, "recommend", fileName,response);
							file.transferTo(targetFile);
							
							SysUpload sysUpload = new SysUpload();
							sysUpload.setFileSize((int)file.getSize());
							sysUpload.setFileFullPath(relPath+fileName);
							sysUpload.setCreatedTime(MioUtil.getYMDHMSDateTime(new Date()));
							sysUpload.setFuncId("recommend");
							sysUpload = sysUploadService.save(sysUpload);
							//拼接上传文件的id
							if(count == 1){
								productImg = relPath+fileName;
								entity.setsImgUrl(productImg);
							}
							entity.setmImgUrl(sysUpload.getFileFullPath());
							sysUploads.add(sysUpload);
							
						}
					}
					// 记录上传该文件后的时间
					int finaltime = (int) System.currentTimeMillis();
					System.out.println(finaltime - pre);
				}
				
				//保存产品信息
				entity.setCreatedTime(MioUtil.getYMDHMSDateTime(new Date()));
				entity = this.getService().save(entity);
			}
		} catch (Exception e) {
			e.printStackTrace();
			resultMap.put("success", false);
			resultMap.put("info", e.getMessage());
		}
		resultMap.put("success", true);
		resultMap.put("info", entity);
		return resultMap;
	}

	//ɾ����¼
	@RequestMapping("/delRecommand.do")
	public @ResponseBody
	MessageResult delRecommand(Recommand entity) {
		return this.delete(entity);
	}
	
	//�޸ļ�¼
	@RequestMapping("/updateRecommand.do")
	public @ResponseBody
	MessageResult updateRecommand(Recommand entity, HttpServletRequest request,
			HttpServletResponse response) throws IllegalStateException, IOException  {
		Recommand old = this.getService().get(entity.getId());
		boolean change[] = new boolean[2];
		int flag = 1;
		int change0 = Integer.parseInt(request.getParameter("change0"));
		if(change0>0){
			change[0] = true;
		}
		int change1 = Integer.parseInt(request.getParameter("change1"));
		//表示修改
		if(change1>0){
			change[flag] = true;
		//表示清除
		}else if(change1 == 0){
			entity.setmImgUrl("");
		}
		try {
			// 创建一个通用的多部分解析器
			CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
					request.getSession().getServletContext());
			// 判断 request 是否有文件上传,即多部分请求
			if (multipartResolver.isMultipart(request)) {
				String relPath = "/upload/recommend/";
				// 转换成多部分request
				MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
				// 取得request中的所有文件名
				Iterator<String> iter = multiRequest.getFileNames();
				while (iter.hasNext()) {
					if(change[flag]){
						System.out.println(iter.hasNext());
						// 记录上传过程起始时的时间，用来计算上传时间
						int pre = (int) System.currentTimeMillis();
						// 取得上传文件
						MultipartFile file = multiRequest.getFile(iter.next());
						if (file != null) {
							// 取得当前上传文件的文件名称
							String fileName = file.getOriginalFilename();
							// 如果名称不为“”,说明该文件存在，否则说明该文件不存在
							if (!fileName.trim().equals("")) {
								System.out.println(fileName);						
								File targetFile = MioUtil.getUploadFile(request, "recommend", fileName,response);
								file.transferTo(targetFile);
								
								SysUpload sysUpload = new SysUpload();
								sysUpload.setFileSize((int)file.getSize());
								sysUpload.setFileFullPath(relPath+fileName);
								sysUpload.setCreatedTime(MioUtil.getYMDHMSDateTime(new Date()));
								sysUpload.setFuncId("recommend");
								sysUpload = sysUploadService.save(sysUpload);
								entity.setmImgUrl(sysUpload.getFileFullPath());
								
							}
						}
						// 记录上传该文件后的时间
						int finaltime = (int) System.currentTimeMillis();
						System.out.println(finaltime - pre);
					}
				}			
				//保存产品信息
				if(entity.getCreatedTime() == null){
					entity.setCreatedTime(old.getCreatedTime());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return this.update(entity);
	}

	/**
	 * 美美推荐分页查询
	 * @param searchEntitySch 美美推荐实体类对象
	 * @param pageSize  显示数量
	 * @param page 当前为第几页
	 * @param isDeletedSch 查询为删除的数据 isDeletedSch=0
	 * @return
	 */
	@RequestMapping("/listRecommand.do")
	public @ResponseBody
	GridResult listRecommand(RecommandSch searchEntitySch) {
		return this.query(searchEntitySch);
	}

	
	//������ѯ���������м�¼
	@RequestMapping("/listAllRecommand.do")
    public @ResponseBody Object listAllRecommand(RecommandSch searchEntitySch) {
        return this.queryAll(searchEntitySch);
    }

    /**
     * 通过id查询对象
     * @param entity
     * @return
     */
	@RequestMapping("/getRecommandById.do")
    public @ResponseBody Recommand getRecommandById(Recommand entity) {
        return this.getService().get(entity.getId());
    }
	
	/**
	 * 添加美美推荐，并且保存产品图片
	 * 
	 * @param searchEntitySch
	 * @return
	 */
	@RequestMapping("/saveRecommend.do")
	public @ResponseBody Map<String, Object> saveProductInfo(HttpServletRequest request, MultipartFile file,
			Recommand recommand) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			String path = request.getSession().getServletContext().getRealPath("upload/recommend");
			String relPath = "/upload/recommend/";
			String fileName = file.getOriginalFilename();
			// 大图
			File dir = MioUtil.createDir(path);
			File targetFile = MioUtil.createFile(dir, fileName);
			// 小图
			String fileNameSmall = "s_" + file.getOriginalFilename();
			File targetFileSmall = MioUtil.createFile(dir, fileNameSmall);

			if (targetFile != null) {
				FileUtils.writeByteArrayToFile(targetFile, file.getBytes());
				// 同时保存小图到相应的文件中
				Thumbnails.of(targetFile).size(MioConstants.THUMB_SMALL_WIDTH, MioConstants.THUMB_SMALL_HEIGHT)
						.toFile(targetFileSmall);
				recommand.setmImgUrl(relPath + fileName);
				recommand.setsImgUrl(relPath + fileNameSmall);
				recommand.setCreatedTime(MioUtil.getYMDHMSDateTime(new Date()));
				recommand = this.getService().save(recommand);
				resultMap.put("success", true);
				resultMap.put("info", recommand);
			} else {
				resultMap.put("success", false);
				resultMap.put("info", MioInfoTips.CREATE_FILE_FAIL);
			}

		} catch (Exception e) {
			e.printStackTrace();
			resultMap.put("success", false);
			resultMap.put("info", e.getMessage());
		}
		return resultMap;

	}
	
	/**
     * 修改美美推荐内容
     * @param entity
     * @return
     */
	@RequestMapping("/forwardRecommandDetail.do")
    public ModelAndView forwardRecommandDetail(Recommand entity) {
		ModelAndView modelAndView = new ModelAndView("manager/recommandDetail.jsp");
        Recommand recommand =  this.getService().get(entity.getId());
        modelAndView.addObject("recommand", recommand);
        return modelAndView;
    }
	
	/**
	 * 清除文件
	 * @param product
	 * @param index
	 */
	public void clearFile(Product product,int index){
		String picId[] = product.getPicId().split(",");
		String picIds = "";
		for(int i = 0; i<picId.length; i++){
			if(i+1 == index){
				sysUploadService.del(sysUploadService.get(picId[i]));
			}else{
				picIds = picId[i]+",";
			}
		}
		picIds = picIds.substring(0,picIds.length()-1);
		product.setPicId(picIds);	
	}
}